#include<iostream>
#include<string>
using namespace std;

//leetcode8

class Solution {
public:
    int myAtoi(string s) {
        int sz = s.size();
        long ret = 0;
        int flag = 1;
        int pos = 0;
        bool judge = true;
        while (pos < sz)
        {
            if (s[pos] == '+' || s[pos] == '-')
            {
                if (judge == false)
                    return 0;
                judge = false;
                if (s[pos++] == '-')
                    flag = -1;
                continue;
            }
            if (s[pos] >= '0' && s[pos] <= '9')
                break;
            else if (s[pos] == ' ' && judge)
                ++pos;
            else
                return 0;
        }
        //cout<<INT_MAX<<endl;
        for (int i = pos; i < sz; ++i)
        {
            if (s[i] >= '0' && s[i] <= '9')
            {
                ret *= 10;
                ret += s[i] - '0';
            }
            else
            {
                break;
            }
            if (ret > INT_MAX - 1)
            {
                if (flag > 0)
                {
                    return INT_MAX;
                }
                else
                {
                    if (ret == INT_MAX)
                        return INT_MAX * -1;
                    return INT_MIN;
                }
            }
        }
        return ret * flag;
    }
};